'use strict'
const path = require('path')
const webpack = require('webpack')
const defaultSettings = require('./src/settings.js')
const { buildDate, script } = require('./build-info.js')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title // page title
const { packName } = require('./package.json')

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// 引入等比适配插件
const px2rem = require('postcss-px2rem')

// 配置基本大小
const postcss = px2rem({
  // 基准大小 baseSize，需要和rem.js中相同
  remUnit: 16
})

module.exports = {
  transpileDependencies: ['@xdh/my', 'ol'],
  chainWebpack(chain) {
    chain.resolve.alias.set('$ui', '@xdh/my/ui/lib')
  }
}

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: process.env.NODE_ENV === 'development' ? '/' : '/cms/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    headers: {
      'Access-Control-Allow-Origin': '*' // 主应用获取子应用时跨域响应头
    },
    proxy: {
      '/winglinks': {
        target: 'http://127.0.0.1:9201',
        changeOrigin: true,
        pathRewrite: {
          '^/winglinks': ''
        }
      },
      // '/winglinks': {
      //   target: 'http://172.26.1.56:80/',
      //   changeOrigin: true
      // },
      // '/cms': {
      //   target: 'http://127.0.0.1:9000/',
      //   changeOrigin: true,
      //   pathRewrite: {
      //     '^/cms': ''
      //   },
      //   onProxyReq: (proxyReq, req) => {
      //     if (req.body) {
      //       const bodyData = JSON.stringify(req.body)
      //       proxyReq.setHeader('Content-Type', 'application/json')
      //       proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
      //       proxyReq.write(bodyData)
      //     }
      //   }
      // },
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://172.26.1.56:80/itps',
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      },
      '/paas/paas-app': {
        target: 'http://192.168.230.220:8121',
        changeOrigin: true,
        pathRewrite: {
          '^/paas/paas-app': ''
        }
      },
      '/kafkaRes/paas-kafka': {
        target: 'http://172.20.1.9:13105/',
        changeOrigin: true,
        pathRewrite: {
          '^/kafkaRes/paas-kafka': '/kafkaRes/paas-kafka'
        }
      },
      '/jcw40': {
        target: 'http://172.20.1.9:13845/jcw40',
        changeOrigin: true,
        pathRewrite: {
          '^/jcw40': ''
        }
      }
    },
    after: require('./mock/mock-server.js')
  },
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          postcss
        ]
      }
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    output: {
      // 把子应用打包成 umd 库格式
      library: `${packName}-[name]`,
      libraryTarget: 'umd',
      jsonpFunction: `webpackJsonp_${packName}`
    },
    plugins: [

      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'windows.jQuery': 'jquery'
      })

    ]
  },
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    config.plugins.delete('prefetch')
    config.module
      .rule('xml-loader')
      .test(/\.xml$/)
      .use('xml-loader')
      .loader('xml-loader')
      .end()
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config.module
      .rule('hdr')
      .test(/\.(hdr|fbx)$/)
      .include.add(resolve('src/assets/images/phm'))
      .end()
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'static/other/[sha512:hash:base64:7].[ext]'
      })
      .end()

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          // 打包时间
          config
            .plugin('html')
            .tap(args => {
              args[0].minify.removeComments = false
              args[0].buildInfo = `打包时间：${buildDate}`
              args[0].script = `打包脚本：${script}`
              args[0].cesiumPath = process.env.VUE_APP_CESIUM_PATH
              return args
            })
            .end()
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
